﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFCoreIdentitySample.Domain.Core;
using EFCoreIdentitySample.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace EFCoreIdentitySample.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;
        public AccountController(SignInManager<ApplicationUser> signInManager
            , UserManager<ApplicationUser> userManager)
        {
            _signInManager = signInManager;
            _userManager = userManager;
        }

        [AllowAnonymous]
        public IActionResult Register(string returnUrl = null)
        {
            ViewData["ReturlUrl"] = returnUrl;
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Register(RegisterVm vm, string returnUrl = null)
        {
            ViewData["ReturlUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser()
                {
                    Email = vm.Email,
                    UserName = vm.Email,
                    NormalizedUserName = vm.Email,
                    NormalizedEmail = vm.Email
                };
                var identityResult = await _userManager.CreateAsync(user, vm.Password);
                if (identityResult.Succeeded)
                {
                    await _signInManager.SignInAsync(user, new AuthenticationProperties() { IsPersistent = false });
                    //return RedirectToAction("Index", "Home");
                    return RedirectToLocal(returnUrl);
                }
            }
            else
            {
                foreach (var error in ModelState.Root.Errors)
                {
                    ModelState.AddModelError("", error.ErrorMessage);
                }
            }
            return View(vm);
        }


        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            ViewData["ReturlUrl"] = returnUrl;
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginVm vm, string returnUrl = null)
        {
            ViewData["ReturlUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(vm.Email);
                if (!user.Password.Equals(vm.Password))
                {
                    ModelState.AddModelError("Password error.","密码验证失败，请稍后重试。");
                    return View();
                }
                await _signInManager.SignInAsync(user, new AuthenticationProperties() { IsPersistent = false });  
                return RedirectToLocal(returnUrl);
            }
            else
            {
                foreach (var error in ModelState.Root.Errors)
                {
                    ModelState.AddModelError("",error.ErrorMessage);
                }
            }
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            //await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            //await HttpContext.SignOutAsync();
            await _signInManager.SignOutAsync();
            return RedirectToAction("Index", "Home");
        }


        private IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }


    }
}